package ru.pb.global.compiler;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MemoryClassLoader extends ClassLoader implements Iterable<String>
{
	private final Map<String, MemoryJavaByteCode> _bytes = new TreeMap<String, MemoryJavaByteCode>();

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException
	{
		MemoryJavaByteCode byteCode = _bytes.get(name);
		if(byteCode == null)
		{
			return super.findClass(name);
		}
		byte[] bytecode = byteCode.getBytes();

		return defineClass(name, bytecode, 0, bytecode.length);
	}

	public void addClass(MemoryJavaByteCode code)
	{
		_bytes.put(code.getName().replace("/", "."), code);
	}

	public void free()
	{
		_bytes.clear();
	}

	@Override
	public Iterator<String> iterator()
	{
		return _bytes.keySet().iterator();
	}
}
